package app.nbdevices.utils;


import org.apache.commons.codec.binary.Base64;
import java.time.format.DateTimeFormatter;

public class ConvertUtil {
    //Base64编解码器  经过测试  java.utils.Base64存在线程安全问题  故使用apache的编解码器
    private static final Base64 BASE_64_CODEC=new Base64();

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

    private static final DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

    public static Base64 getBase64Codec(){
        return BASE_64_CODEC;
    }
    public static DateTimeFormatter getFormatter(){return formatter;}
    public static DateTimeFormatter getFormatters(){return formatters;}
    public static String byteToString(byte b){

        String s=Integer.toHexString(b&0xff);
        if(s.length()>2){
            return s.substring(s.length()-2);
        }else if(s.length()<2){
            return 0+s;
        }else{
            return s;
        }
    }
    public static byte[] arraySub(byte[] src,int start,int end){
        int length=end-start+1;
        byte[] res=new byte[length];
        for(int i=0;i<length;i++){
            res[i]=src[start+i];
        }
        return res;
    }
    public static String DecimaltoBcd(String str){
        String b_num="";
        for (int i = 0; i < str.length(); i++) {

            String b = Integer.toBinaryString(Integer.parseInt(str.valueOf(str.charAt(i))));

            int b_len=4-b.length();

            for(int j=0;j<b_len;j++){
                b="0"+b;
            }
            b_num+=b;
        }
        return b_num;
    }
    public static String HextoBcd(String hex){

        int decimal = Integer.parseInt(hex,16);

        String bcd = DecimaltoBcd(String.valueOf(decimal));

        return bcd;
    }

    /**
     * 求校验和的算法
     * @param b 需要求校验和的字节数组
     * @return 校验和
     */
    public static byte sumCheck(byte[] b,int len){
        int sum = 0;
        for(int i = 0; i < len; i++){
            sum = sum + b[i]%256;
        }
        return (byte) (sum & 0xff);
    }

}
